﻿// Copyright 2009 Mike Geise
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

namespace Falcon.Core.Validators
{
	using Falcon.Core.Domain;
	using Falcon.Core.Domain.Enums;
	using Falcon.Core.Domain.Repositories;
	using Falcon.Core.Extensions;
	using Falcon.Core.Validation.Validators;

	public class UserMessagePreferenceValidator : IValidator
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="UserMessagePreferenceValidator"/> class.
		/// </summary>
		public UserMessagePreferenceValidator()
		{
			this.UserRepository = Application.Resolve<IUserRepository>();
			this.UserContactRepository = Application.Resolve<IUserContactRepository>();
		}

		/// <summary>
		/// Gets or sets the user repository.
		/// </summary>
		/// <value>The user repository.</value>
		public IUserRepository UserRepository
		{
			get;
			private set;
		}

		public IUserContactRepository UserContactRepository
		{
			get;
			private set;
		}

		/// <summary>
		/// Validates the specified value.
		/// </summary>
		/// <param name="value">The value.</param>
		/// <param name="against">The against.</param>
		/// <returns></returns>
		public bool Validate(object value, object against)
		{
			var name = value as string;

			if (!name.HasValue())
			{
				return true;
			}

			var identity = User.Identity;

			if (identity.IsAuthenticated())
			{
				if (identity.IsAdministrator || identity.IsModerator)
				{
					return true;
				}

				var user = UserRepository.GetBy(new UserSpecification
				{
					Name = name
				});

				if (user == null)
				{
					return false;
				}

				if (!user.Preference.IsMessagingEnabled)
				{
					return false;
				}

				if (user.Preference.IsMessagingRetrictedEnabled)
				{
					var count = UserContactRepository.Count(new UserContactSpecification
					{
						UserId = user.Id,
						ContactId = identity.Id,
						Status = new[] { UserContactStatus.Normal, UserContactStatus.FriendApproved }
					});

					return count > 0;
				}

				return true;
			}

			return false;
		}
	}
}